import { t } from 'i18next'
import { fetchChangeMTVmp, fetchGetMtVmpParam, fetchStartMTVmp, fetchStopMTVmp } from '@/api/manager/mtVmp'
import useLock from '@/hooks/useLock'
import { Button, CheckBox, Message, Modal, RadioGroup, Space } from '@kedacom/react-next'
import { useRequest } from 'ahooks'
import React, { useEffect, useRef, useState } from 'react'
import Alert from '../Alert'
import MemberList from '../MemberList'
import VmpView from './VmpView'
import { ViewRef } from './VmpView/interface'
import { store, useAutoVmpStore } from './store'
import { StyledWrap } from './style'
import { transMtVmpParam } from './translator'
import { useMccStore } from '@/pages/manager/store'
import { AutoVmpData } from '@/api/manager/mtVmp/interface'

export default function AutoVmpDialog() {
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)
	const superMtNum = useMccStore((state) => state.mccInfo.superMtNum)
	const { isOpen, mode, data, mtInfo, update, updateData, onInit, onClose, onConfirm, reset } = useAutoVmpStore(
		(state) => ({
			isOpen: state.isOpen,
			mode: state.mode,
			data: state.data,
			mtInfo: state.mtInfo,
			update: state.update,
			updateData: state.updateData,
			onInit: state.onInit,
			onClose: state.onClose,
			onConfirm: state.onConfirm,
			reset: state.reset,
		})
	)
	const [isModify, setIsModify] = useState(false)
	const loadMaskRef = useRef<any>(null)
	const viewRef = useRef<ViewRef | null>(null)
	const mtid = mtInfo?.mtid ?? ''
	const { run } = useRequest(() => fetchGetMtVmpParam(meetingMoid, mtid), {
		manual: true,
		onSuccess: (res) => {
			loadMaskRef.current?.hide() //隐藏蒙层
			if (res && res.success) {
				let _data = transMtVmpParam(res.data)
				//获取接口不给state值，res.data为null是未开启，有值是开启
				updateData({ ..._data, state: res.data ? 1 : 0 })
			} else {
				handleClose()
				Alert(t('获取终端自主多画面信息失败'))
			}
		},
	})
	useEffect(() => {
		if (isOpen) {
			onInit()
			if (mode === 'mtVmp') {
				loadMaskRef.current = Message.loading(t('正在处理，请稍候……'))
				run()
			}
		}
	}, [isOpen])
	useEffect(() => {
		store.setState({
			msgHandle: (vmpData) => {
				if (mode !== 'mtVmp' || isModify || vmpData.vmp_mt.mt_id !== mtid) return
				if (vmpData.state === 0) {
					updateData({ ...data, state: 0 })
				} else {
					let _data = transMtVmpParam(vmpData)
					updateData(_data)
				}
			},
		})
	}, [mode, isModify, mtid, updateData])
	const handleClose = () => {
		reset()
		setIsModify(false)
		onClose?.()
	}
	const getParam = (): AutoVmpData => ({
		meeting_moid: meetingMoid,
		mode: data.mode,
		show_mt_name: data.show_mt_name,
		layout: data.mode === 2 ? 0 : viewRef.current?.getStyle() ?? 0,
		vmp_mt: {
			mt_id: mtInfo?.mtid ?? '',
			account: mtInfo?.account ?? '',
			account_type: mtInfo?.accountType ?? 1,
			name: mtInfo?.INITIAL_NAME ?? '',
		},
		members:
			data.mode === 2
				? []
				: viewRef.current?.getValue().map((item) => ({
						mt_id: item.mt_id ?? '',
						account: item.account ?? '',
						account_type: item.account_type ?? 1,
						name: item.name ?? '',
						chn_idx: item.chn_idx,
						member_type: item.member_type,
				  })) ?? [],
	})
	const handleOk = () => {
		let param = getParam()
		onConfirm?.({
			mode: param.mode,
			show_mt_name: param.show_mt_name,
			layout: param.layout,
			members: param.members,
			id: '',
			name: '',
			voice_hint: 0,
			broadcast: 0,
			except_self: 0,
		})
		handleClose()
	}
	const startMTVmpReq = useLock(async (param) => {
		await fetchStartMTVmp(meetingMoid, param).then((res) => {
			if (res.success) {
				setTimeout(function () {
					loadMaskRef.current?.hide()
				}, 1500)
				setIsModify(false)
				updateData({ ...data, state: 1 })
			} else {
				loadMaskRef.current?.hide()
				Alert(res.description ?? t('开始自主画面合成失败'))
			}
		})
	})
	const changeMTVmpReq = useLock(async (param) => {
		await fetchChangeMTVmp(meetingMoid, mtid, param).then((res) => {
			if (res.success) {
				setTimeout(function () {
					loadMaskRef.current?.hide()
				}, 1500)
				setIsModify(false)
				updateData({ ...data, state: 1 })
			} else {
				loadMaskRef.current?.hide()
				Alert(res.description ?? t('修改自主画面合成失败'))
			}
		})
	})
	const stopMTVmpReq = useLock(async () => {
		await fetchStopMTVmp(meetingMoid, mtid).then((res) => {
			if (res.success) {
				setTimeout(function () {
					loadMaskRef.current?.hide()
				}, 1500)
				setIsModify(false)
				updateData({ ...data, state: 0 })
			} else {
				loadMaskRef.current?.hide()
				Alert(res.description ?? t('停止自主画面合成失败'))
			}
		})
	})
	const handleStart = () => {
		loadMaskRef.current = Message.loading(t('正在处理，请稍候……'))
		let param = getParam()
		startMTVmpReq(param)
	}
	const handleChange = () => {
		loadMaskRef.current = Message.loading(t('正在处理，请稍候……'))
		let param = getParam()
		changeMTVmpReq(param)
	}
	const handleStop = () => {
		loadMaskRef.current = Message.loading(t('正在处理，请稍候……'))
		stopMTVmpReq()
	}
	return (
		<Modal
			className="auto-vmp-dialog"
			open={isOpen}
			width={858}
			height={535}
			title={t('自主多画面')}
			needFooter={false}
			onCancel={handleClose}
		>
			<StyledWrap>
				<div className="content">
					<div className="view">
						<div className="mode-wrap">
							<span className="label">{t('模式选择')}</span>
							<RadioGroup
								value={data.mode}
								options={[
									{ label: t('自动自主多画面'), value: 2, width: 140 },
									{ label: t('定制画面合成'), value: 1, width: 140 },
								]}
								onChange={(e, val) => {
									setIsModify(true)
									let _data = { ...data }
									if (val === 1) {
										_data.mode = 1
										_data.layout = 5
									} else {
										_data.mode = 2
										_data.layout = 0
									}
									_data.members = []
									updateData(_data)
								}}
							></RadioGroup>
						</div>
						{data.mode === 2 && <div className="dynamic-view">{t('自动')}</div>}
						{data.mode === 1 && (
							<VmpView
								ref={viewRef}
								style={data.layout}
								members={data.members}
								onSelect={() => {
									setIsModify(true)
								}}
								onBoxChange={() => {
									setIsModify(true)
								}}
							/>
						)}
					</div>
					{data.mode === 1 && (
						<div className="list">
							<MemberList height={superMtNum ? 370 : 348} />
						</div>
					)}
				</div>
				<div className="bottom">
					<div className="left-wrap">
						<CheckBox
							checked={Boolean(data.show_mt_name)}
							onChange={(e, val) => {
								setIsModify(true)
								updateData({ ...data, show_mt_name: val ? 1 : 0 })
							}}
						>
							{t('显示终端名称')}
						</CheckBox>
						<span className="tip">
							<span className="icon"></span>
							{t('请拖拽与会方至指定的画面中')}
						</span>
					</div>
					<Space className="right-wrap">
						{mode === 'mtVmp' ? (
							data.state !== 1 ? (
								<Button className="start" width={80} style={{ padding: 0 }} onClick={handleStart}>
									{t('开始画面合成')}
								</Button>
							) : isModify ? (
								<Button className="change" width={80} style={{ padding: 0 }} onClick={handleChange}>
									{t('确认修改')}
								</Button>
							) : (
								<Button className="stop" width={80} style={{ padding: 0 }} onClick={handleStop}>
									{t('停止画面合成')}
								</Button>
							)
						) : (
							<Button className="confirm" width={80} onClick={handleOk}>
								{t('确认')}
							</Button>
						)}
						<Button className="cancel" width={80} onClick={handleClose}>
							{t('取消')}
						</Button>
					</Space>
				</div>
			</StyledWrap>
		</Modal>
	)
}
